<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" :height="500" @ok="handleSubmit">
    <BasicForm @register="registerForm" name="dataManagementForm" />
    <a-collapse v-if="formModel.before_data || formModel.ping_json" class="collapse-wrapper">
      <a-collapse-panel key="1" :header="formModel.before_data ? '处理前数据(点击展开查看)' : 'ping结果数据'">
        <pre class="json-preview" v-if="formModel.before_data">{{ formatJson(formModel.before_data) }}</pre>
        <pre class="json-preview" v-else>{{ formatJson(formModel.ping_json) }}</pre>
      </a-collapse-panel>
    </a-collapse>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../dataManagement.data';
  import { saveOrUpdate } from '../dataManagement.api';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const isDetail = ref(false);
  const formModel = ref<Recordable>({});
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, scrollToField, getFieldsValue }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !!data?.showFooter;
    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record,
        ...data.model, // ✅ 新增这行来接收协议值
      });
      formModel.value = getFieldsValue();
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(isDetail) ? '详情' : '编辑'));
  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  const formatJson = (jsonStr) => {
    try {
      const jsonObj = JSON.parse(jsonStr);
      return JSON.stringify(jsonObj, null, 2);
    } catch {
      return jsonStr;
    }
  };
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
  // 在现有样式后添加
  .collapse-wrapper {
    margin: 0px 48px;

    :deep(.ant-collapse-content) {
      overflow: auto;
      height: 440px;
    }
    :deep(.ant-collapse-header) {
      padding: 12px 16px !important;
    }
  }
  .json-preview {
    margin: 0 16px; // 左右留白
    padding: 12px; // 增加内边距
  }
</style>
